package com.wish.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

import com.wish.common.MyUtils;


/**
 * @author tantexian
 * @since 2016/7/7
 */
public class AIORobotClient {

    public static void main(String[] args) {
        final int port = args.length >= 1 ? Integer.parseInt(args[0]) : MyUtils.getDefaultPort();
        final String host = args.length >= 2 ? args[1] : MyUtils.getDefaultServerAddr();
        try {
            final AsynchronousSocketChannel asynchronousSocketChannelClient = AsynchronousSocketChannel.open();


            new Thread(new Runnable() {
                public void run() {
                    //CountDownLatch countDownLatch = new CountDownLatch(1);
                    System.out.println(port);
                    asynchronousSocketChannelClient.connect(new InetSocketAddress(host, port));
                    System.out.println(asynchronousSocketChannelClient.isOpen());
                    try {
                        asynchronousSocketChannelClient.write(ByteBuffer.wrap("AIOSimpleClient".getBytes())).get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                    final ByteBuffer buffer = ByteBuffer.allocate(1024);
                   /* asynchronousSocketChannelClient.read(buffer, null, new CompletionHandler<Integer, Object>() {
                        public void completed(Integer result, Object attachment) {
                            System.out.println("AIOSimpleClient == " + new String(buffer.array()));
                        }

                        public void failed(Throwable exc, Object attachment) {

                        }
                    });*/
                    /*try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }*/
                }
            }).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
